package caddy

import (
	"context"
	"gitee.com/Luna-CY/hui-hui/internal/application/app"
	"gitee.com/Luna-CY/hui-hui/internal/interface/application"
	"gitee.com/Luna-CY/hui-hui/internal/logger"
	"gitee.com/Luna-CY/hui-hui/internal/runtime"
	"gitee.com/Luna-CY/hui-hui/internal/toolbox/processor"
	"os"
	"path/filepath"
	"sync"
)

// rootPath Caddy服务器目录
var rootPath = filepath.Join(runtime.ApplicationRoot, "caddy")

// internalConfigPath 内部配置文件路径
var internalConfigPath = filepath.Join(runtime.ConfigRoot, "caddy.v1.json")

// logFolder 日志目录
var logFolder = filepath.Join(rootPath, "logs")

// configFolder 配置目录
var configFolder = filepath.Join(rootPath, "huihui")

// configFilePath Caddy服务器配置文件路径
var configFilePath = filepath.Join(configFolder, "Caddyfile")

// configLoadPath Caddy服务器额外配置加载目录
var configLoadPath = filepath.Join(configFolder, "config.d")

var once sync.Once
var instance *Caddy

// Single 返回Caddy应用单例对象
func Single(processor *processor.Processor) *Caddy {
	once.Do(func() {
		var config = new(application.CaddyConfig)
		config.Websites = map[string]*application.CaddyWebsite{}
		instance = &Caddy{processor: processor}
		instance.SetConfig(config)

		// 本地自检
		if err := instance.CheckLocationState(context.Background()); nil != err {
			logger.GetLogger().Sugar().Errorf("检查Caddy服务状态失败，失败原因: %s", err)

			os.Exit(1)
		}

		// 加载本地配置
		if err := instance.LoadFromDisk(nil, internalConfigPath); nil != err {
			logger.GetLogger().Sugar().Errorf("加载Caddy配置文件失败，失败原因: %s", err)

			os.Exit(1)
		}
	})

	return instance
}

// Caddy Caddy应用定义
type Caddy struct {
	app.Application[application.CaddyConfig]

	processor *processor.Processor
}
